package cetcbigdata.da.service.zhejiang.qitaqingdan;

import cetcbigdata.da.base.DownloadAndUploadMinio;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YuanGongPing
 * @version 0.1
 * @description UtilZheJiang
 * @since 2022/9/19 16:13
 */


public class UtilZheJiang {

    public static JSONObject getHeaders(){
        JSONObject headers = new JSONObject();
        headers.put("Accept", " */*");
        headers.put("Accept-Encoding", " gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh-TW;q=0.9,zh;q=0.8,en-US;q=0.7,en;q=0.6");
        headers.put("Referer", "https://www.zjzwfw.gov.cn/zjservice/matter/list/zeroruns.do?jurisCode=330113&webId=3772");
        headers.put("Host", "www.zjzwfw.gov.cn");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
        return headers;
    }

    public static JSONObject getParams(){
        return new JSONObject();
    }

    /********
     * 获取前言信息
     * @param jxDocument
     * @return
     */
    public static JSONObject geExtraInfo(JXDocument jxDocument){
        try {
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='zjzw-matter-detail-left lf']/div[@class='zjzw-matter-detail-table']//td[@class='zjzw-matter-detail-table-name']");
            for (Object o : rs){
                String key  = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                info.put(key, value);
            }
            return info;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 获取基本信息
     * @param jxDocument
     * @return
     */
    public static JSONObject getBaseInfo(JXDocument jxDocument){
        try {
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='zjzw-procedure-tabItem']//td[@class='zjzw-procedure-tabItem-name']");
            for (Object o : rs){
                String key  = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                info.put(key, value);
            }
            return info;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 线下办事点
     * @param jxDocument
     * @return
     */
    public static JSONObject getOffLinePlace(JXDocument jxDocument){
        try {
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='offLinePlaceWrap']//p/strong");
            for (Object o : rs){
                String key  = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                info.put(key, value);
            }
            return info;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 申请条件信息
     * @param jxDocument
     * @return
     */
    public static JSONObject getApplyConditionInfo(JXDocument jxDocument){
        try {
            // 基本信息
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='zjzw-apply']/p/strong");
            for (Object o : rs){
                String key  = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                info.put(key, value);
            }
            return info;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 申报材料信息
     * @param jxDocument
     * @return
     */
    public static List<JSONObject> getApplicationMaterialsInfo(JXDocument jxDocument){
        try {
            // 基本信息
            List<JSONObject> applicationMaterialList = new ArrayList<>();
            List<Object> rs = jxDocument.sel("//*[@class='sbcl_table_con']//div[@class='prev lf']//span[@class='clmc_con']/p");
            int index = 0;
            for (Object o : rs){
                JSONObject applicationMaterialItem = new JSONObject();
                String name  = ((Element) o).attr("title");
                List<Object> applicationMaterials = jxDocument.sel("//*[@class='sbcls swiper-container']//div[@class='sbcl_tables_content swiper-slide']//div[@class='sbcl_tables_item']");

                applicationMaterialItem.put("材料名称", name);
                applicationMaterialItem.put("来源渠道", ((Element) applicationMaterials.get(index)).child(0).text());
                applicationMaterialItem.put("材料类型", ((Element) applicationMaterials.get(index)).child(1).text());
                applicationMaterialItem.put("材料形式", ((Element) applicationMaterials.get(index)).child(2).text());
                applicationMaterialItem.put("纸质材料份数", ((Element) applicationMaterials.get(index)).child(3).text());
                applicationMaterialItem.put("纸质材料规格", ((Element) applicationMaterials.get(index)).child(4).text());
                applicationMaterialItem.put("材料必要性", ((Element) applicationMaterials.get(index)).child(5).text());

                // 判断是否含有附件
                List<JSONObject> enclosureList = new ArrayList<>();
                if(((Element) applicationMaterials.get(index)).child(6).child(0).children().size() > 0 ){
                    // 含有附件
                    Elements elements =  ((Element) applicationMaterials.get(index)).child(6).child(0).children();
                    for(Element e : elements){
                        JSONObject enclosure = new JSONObject();
                        String fileName = e.text();
                        String fileUrl = "https:" +  e.attr("href");
                        enclosure.put("文件名", fileName);
                        enclosure.put("文件原地址", fileUrl);
                        enclosure.put("minioId", fileDownloadAndUploadMinioGetImage(fileUrl, getFileNameFromPath(fileUrl)) );
                        enclosureList.add(enclosure);
                    }
                }
                applicationMaterialItem.put("材料下载", enclosureList);
                applicationMaterialItem.put("受理标准", ((Element) applicationMaterials.get(index)).text());
                applicationMaterialItem.put("填报须知", ((Element) applicationMaterials.get(index)).text());
                applicationMaterialItem.put("备注", ((Element) applicationMaterials.get(index)).text());
                applicationMaterialList.add(applicationMaterialItem);
                index ++;
            }
            return applicationMaterialList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 办理流程信息
     * @param jxDocument
     * @return
     */
    public static JSONObject getProcessFlowTableInfo(JXDocument jxDocument){
        try {
            JSONObject out = new JSONObject();
            List<JSONObject> processFlowTableList = new ArrayList<>();
            // 环节、 办理时限、 办理人员 、审查标准、 办理结果
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='Process-flow-table']/span/table/tbody/tr");
            for (Object o : rs){
                if(((Element) o).attr("class").equals("firstRow")){
                    // 跳过表头 tr
                    continue;
                }
                info.put("环节",      ((Element) o).children().size() >= 1 ? ((Element) o).child(0).text() : "");
                info.put("办理时限",  ((Element) o).children().size() >= 2 ? ((Element) o).child(1).text() : "");
                info.put("办理人员",  ((Element) o).children().size() >= 3 ? ((Element) o).child(2).text() : "");
                info.put("审查标准",  ((Element) o).children().size() >= 4 ? ((Element) o).child(3).text() : "");
                info.put("办理结果",  ((Element) o).children().size() >= 5 ? ((Element) o).child(4).text() : "");
                processFlowTableList.add(info);
            }

            // 解析办理流程图
            JSONObject processFlowImage = new JSONObject();
            Object image = jxDocument.selOne("//*[@class='lc_btn']");
            String imageUrl = ((Element) image).attr("onclick");
            imageUrl = imageUrl.replace("window.open(encodeURI('", "").replace("'));", "");
            imageUrl = "https://www.zjzwfw.gov.cn" + imageUrl;
            processFlowImage.put("原地址", imageUrl);
            processFlowImage.put("名称", "办理流程图.png");
            processFlowImage.put("minioId", fileDownloadAndUploadMinioGetImage(imageUrl, "办理流程图.png"));
            out.put("办理流程", processFlowTableList);
            out.put("办理流程图", processFlowImage);
            return out;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /********
     * 设定依据
     * @param jxDocument
     * @return
     */
    public static List<JSONObject> getSettingBasisInfo(JXDocument jxDocument){
        try {
            List<JSONObject> settingBasisList = new ArrayList<>();
            List<Object> rs = jxDocument.sel("//*[@class='setting-basis']/table");
            for(int i = 1, len = rs.size(); i <= len; i++){
                List<Object> items = jxDocument.sel(String.format("//*[@class='setting-basis']//table[%s]//td[@class='setting-basis-name']", i));
               JSONObject settingBasis = new JSONObject();
                for (Object o : items){
                    String key  = ((Element) o).text();
                    String value = ((Element) o).nextElementSibling().text();
                    settingBasis.put(key, value);
                    settingBasisList.add(settingBasis);
                }
            }
            return settingBasisList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /********
     * 收费标准
     * @param jxDocument
     * @return
     */
    public static JSONObject getChargeStandardInfo(JXDocument jxDocument){
        try {
            // 基本信息
            JSONObject info = new JSONObject();
            List<Object> rs = jxDocument.sel("//*[@class='charge-standard']//p/strong");
            for (Object o : rs){
                String key  = ((Element) o).text();
                String value = ((Element) o).nextElementSibling().text();
                info.put(key, value);
            }
            return info;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /********
     * 常见问题
     * @param jxDocument
     * @return
     */
    public static List<JSONObject> getQuestionInfo(JXDocument jxDocument){
        try {
            List<JSONObject> questionList = new ArrayList<>();
            int size = jxDocument.sel("//*[@class='common-problem']/table/tbody/tr").size();
            for(int i = 1; i <= size; i++){
                JSONObject info = new JSONObject();
                List<Object> rs = jxDocument.sel(String.format("//*[@class='common-problem']/table/tbody/tr[%s]//p[@class='question clearfix']", i));
                for (Object o : rs){
                    String key  = ((Element) o).text();
                    String value = ((Element) o).nextElementSibling().text();
                    info.put("问题", key);
                    info.put("回答", value);
                }
                questionList.add(info);
            }
            return questionList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private static String fileDownloadAndUploadMinioGetImage(String url, String fileName ) throws Exception {
        return DownloadAndUploadMinio.getInstance().downloadGet(
                url,
                getHeaders(),
                getParams(),
                fileName
        );
    }

    private static  String getFileNameFromPath(String fName){
        fName = fName.trim();
        String fileName = fName.substring(fName.lastIndexOf("/")+1);
        return fileName;
    }

}
